/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.portalnahouby.implementation.daoimplementation;

import cz.muni.fi.pa165.portalnahouby.implementation.daointerface.ForestDAO;
import cz.muni.fi.pa165.portalnahouby.implementation.entity.Forest;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation of ForestDAO interface
 *
 * @author Tomáš Čejka
 */
@Repository
@Transactional
public class ForestDAOImpl implements ForestDAO {
    
@PersistenceContext
    private EntityManager em;
    
    @Override
    public void addForest(Forest forest) {
        if (forest == null) {
            throw new IllegalArgumentException("Forest can not be null.");
        }

        if (forest.getId() != null) {
            throw new IllegalArgumentException("Id of forest must be null");
        }

        em.persist(forest);
    }

    @Override
    public void editForest(Forest forest) {
        if (forest == null) {
            throw new IllegalArgumentException("Forest can not be null.");
        }

        if (forest.getId() == null) {
            throw new IllegalArgumentException("Id of forest can not be null.");
        }

        em.merge(forest);
    }

    
    @Override
    public void deleteForest(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("Id of forest can not be null.");
        }

        Forest forest = em.find(Forest.class, id);

        em.remove(forest);
    }

    
    @Override
    public Forest findForest(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("Id of forest can not be null.");
        }

        Forest forest = em.find(Forest.class, id);
        return forest;
    }
    
    @Override
    public List<Forest> getAllForests() {
        return em.createQuery("SELECT f FROM Forest f", Forest.class).getResultList();
    }
}
